#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/8 17:27
# @Author  : jeff
# @FileName: sqlalchemy_aspect
from sqlalchemy import event
from src.model.base_model import db
from loguru import logger


def sql_loguru(app):
    """
    SQL log, print SQL statements, DB middleware, can do some business processing before and after operating DB
    :param app:
    :return:
    """
    with app.app_context():
        @event.listens_for(db.engine, "before_cursor_execute")
        def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
            with db.session.no_autoflush, app.app_context():
                logger.info(f"Start sql: {statement} with params: {parameters}")
    with app.app_context():
        @event.listens_for(db.engine, "after_cursor_execute")
        def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
            with db.session.no_autoflush, app.app_context():
                logger.info("sql end")